<script setup lang="jsx">

import {
  AddIcon,
  CheckCircleFilledIcon,
  CloseCircleFilledIcon,
  ErrorCircleFilledIcon,
  CryLoudlyIcon,
  EmoEmotionalIcon,
  SerenityIcon,
  Excited1Icon,
  SearchIcon, StarIcon
} from "tdesign-icons-vue-next";
import {computed, reactive, ref, onMounted} from 'vue';
import {getGrade, listPageActivityData, submitGrade, updateSelfGrade} from "@/api/activity.js";
import {useUserStore} from "@/stores/user.js";
import {submitFeedback} from "@/api/feedback.js";
import {MessagePlugin} from "tdesign-vue-next";

const userStore = useUserStore()
// 搜索 --------------------------------------------------------------------------

const searchValue = ref('');
const onClear = () => {
  console.log('clear');
  search();
};
const onBlur = () => {
  console.log('blur');
  if (searchValue.value === '') {
    search()
  }
};

const search = async () => {
  const res = await listPageActivityData(userStore, pageSize.value,searchValue.value, current.value)
  data.value = res.data.data.records
  total.value = res.data.data.total
}

// 表格数据 ------------------------------------------------------------------------
const data = ref([])

const stripe = ref(true);
const bordered = ref(false);
const hover = ref(true);
const size = ref('medium');
const showHeader = ref(true);

// 反馈窗口 ---------------------------------------------------------------------
const feedbackWindowVisible = ref(false)
const chosenRow = reactive({
  activityId: 0,
  activityName: '',

})
const feedbackWindow = (row) => {
  feedbackWindowVisible.value = true
  chosenRow.activityId = row.activity.id
  chosenRow.activityName = row.activity.activityName
  // console.log(chosenRow)
}
const textFeedback = ref('')

const feedbackWindowSubmit = async () => {
  const res = await submitFeedback(userStore, chosenRow.activityId, textFeedback.value)
  if (res.data.data === true) {
    await MessagePlugin.success("提交成功")
    textFeedback.value = ""
    feedbackWindowVisible.value = false
  } else {
    await MessagePlugin.error("提交失败")
  }
}

// 评分窗口 ---------------------------------------------------------------------
const gradeWindowVisible = ref(false)
const gradeStar = ref(0)
const isGraded = ref(false)

const gradeWindow = async (row) => {
  gradeWindowVisible.value = true
  chosenRow.activityId = row.activity.id
  chosenRow.activityName = row.activity.activityName

  const res = await getGrade(userStore, chosenRow.activityId)
  if (res.data.data !== null) {
    gradeStar.value = res.data.data.grade
    textComment.value = res.data.data.comment
    isGraded.value = true
  } else {
    gradeStar.value = 0
    textComment.value = ''
    isGraded.value = false
  }

  // console.log(chosenRow)
}
const textComment = ref('')

const gradeCommentWindowSubmit = async () => {
  if (isGraded.value === true) {
    const res = await updateSelfGrade(userStore, chosenRow.activityId, gradeStar.value, textComment.value)
    if (res.data.data === true) {
      await MessagePlugin.success("更新评分成功")
      textComment.value = ""
      gradeWindowVisible.value = false
    } else {
      await MessagePlugin.error("更新评分失败")
    }
  } else {
    const res = await submitGrade(userStore, chosenRow.activityId, gradeStar.value, textComment.value)
    if (res.data.data === true) {
      await MessagePlugin.success("评分成功")
      textComment.value = ""
      gradeWindowVisible.value = false
    } else {
      await MessagePlugin.error("评分失败")
    }
  }


}

const changeStar = (value) => {
  gradeStar.value = value
}


// -- 表格 --------------------------------------------------------------------
// <t-button theme="primary" size="small" onClick={() => editWindow(row)}>编辑</t-button>

const rateStatusListMap = {
  0: {theme: 'danger',  icon: <CloseCircleFilledIcon/>},
  1: {theme: 'warning', icon: <ErrorCircleFilledIcon/>},
  2: {theme: 'primary', icon: <ErrorCircleFilledIcon/>},
  3: {theme: 'success', icon: <CheckCircleFilledIcon/>},


};
const columns = ref([
  // {colKey: 'activity.id', title: '活动id', width: 40},
  {colKey: 'activity.activityName', title: '活动名称', width: 50},
  {colKey: 'times', title: '参加次数', width: 50},
  {
    colKey: 'groupSuccessRateStr',
    title: '拼团成功率',
    width: 50,
    cell: (h, {row}) => {
      if (row.groupSuccessRate < 0.25) {
        return (
            <t-tag shape="round" theme="danger" variant="light-outline">
              <CryLoudlyIcon />
              {row.groupSuccessRateStr}
            </t-tag>
        )
      } else if (0.25 <= row.groupSuccessRate < 0.5) {
        return (
            <t-tag shape="round" theme="warning" variant="light-outline">
              <EmoEmotionalIcon />
              {row.groupSuccessRateStr}
            </t-tag>
        )
      } else if (0.5 <= row.groupSuccessRate < 0.75) {
        return (
            <t-tag shape="round" theme="primary" variant="light-outline">
              <SerenityIcon />
              {row.groupSuccessRateStr}
            </t-tag>
        )
      } else if (0.75 <= row.groupSuccessRate ) {
        return (
            <t-tag shape="round" theme="primary" variant="light-outline">
              <Excited1Icon />
              {row.groupSuccessRateStr}
            </t-tag>
        )
      }
    },
  },
  {
    colKey: 'option',
    title: '选项',
    width: 150,
    cell: (h, {row}) => {
      return (
          <t-space>
            <t-button theme="primary" size="small" onClick={() => feedbackWindow(row)}>活动反馈</t-button>
            <t-button theme="success" size="small" onClick={() => gradeWindow(row)}>评分评价</t-button>
          </t-space>
      )
    },
  }

]);

const handleRowClick = (e) => {
  // console.log(e);
};


// 初始化数据 ---------------------------------------------
onMounted(async () => {
  const res = await listPageActivityData(userStore, pageSize.value,searchValue.value, current.value)
  data.value = res.data.data.records
  total.value = res.data.data.total
  // console.log(data)

})

// 分页控件 ---------------------------------------------------------------------------------------------
const current = ref(1);
const pageSize = ref(6);
const total = ref(0)

const pageSizeOption = [6, 12, 24]

const onPageSizeChange = async (size) => {
  const res = await listPageActivityData(userStore, pageSize.value,searchValue.value, current.value)
  data.value = res.data.data.records
  total.value = res.data.data.total
};

const onCurrentChange = async (index, pageInfo) => {
  const res = await listPageActivityData(userStore, pageSize.value,searchValue.value, current.value)
  data.value = res.data.data.records
  total.value = res.data.data.total
};

const onChange = (pageInfo) => {
  console.log(pageInfo);
};

</script>

<template>
  <t-layout style="
      height: 100%;                /* 继承父容器高度 */
    ">
    <t-header style="display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 2%;
      padding-right: 1%;
      background-color: #e5e5e5;
      width: auto;">
      <div style="display: flex; justify-content: flex-end; width: 100% ">
        <div style="padding-right: 2%">
          <t-input v-model="searchValue" placeholder="输入活动" borderless clearable @clear="onClear"
                   @blur="onBlur"></t-input>
        </div>
        <div style="padding-right: 2%">
          <t-button shape="circle" theme="primary" @click="search">
            <template #icon>
              <SearchIcon/>
            </template>
          </t-button>
        </div>
<!--        <div>-->
<!--          <t-button shape="circle" theme="primary" @click="">-->
<!--            <template #icon>-->
<!--              <AddIcon/>-->
<!--            </template>-->
<!--          </t-button>-->
<!--        </div>-->
      </div>
    </t-header>
    <t-content
        style="background-color: white; width: 100%; display: flex; align-items: center; justify-content: center">
      <t-space direction="vertical" style="padding: 2%;">

        <!-- 当数据为空需要占位时，会显示 cellEmptyContent -->
        <t-table
            row-key="index"
            :data="data"
            :columns="columns"
            :stripe="stripe"
            :bordered="bordered"
            :hover="hover"
            :table-layout="'fixed'"
            :size="size"
            :show-header="showHeader"
            cell-empty-content="-"
            resizable
            lazy-load
            @row-click="handleRowClick"
        >
        </t-table>
        <t-pagination
            v-model="current"
            v-model:pageSize="pageSize"
            :total=total
            @change="onChange"
            @page-size-change="onPageSizeChange"
            @current-change="onCurrentChange"
            :pageSizeOptions="pageSizeOption"
        />
      </t-space>
    </t-content>

    <!--    反馈窗口-->
    <t-dialog
        v-model:visible="feedbackWindowVisible"
        :header="`${chosenRow.activityName}`+` | 反馈`"
        width="40%"
        @confirm="feedbackWindowSubmit"

    >
      <t-space direction="vertical" style="width: 100%">
        <t-textarea
            v-model="textFeedback"
            placeholder="输入你的反馈或建议吧！"
            :autosize="{ minRows: 10, }"
            :maxcharacter="1000"
        ></t-textarea>
      </t-space>
    </t-dialog>

    <!--    评分窗口-->
    <t-dialog
        v-model:visible="gradeWindowVisible"
        :header="`${chosenRow.activityName}`+` | 评分`"
        width="40%"
        @confirm="gradeCommentWindowSubmit"

    >
      <t-space direction="vertical" style="width: 100%">
        <t-rate @change="changeStar" show-text :value="gradeStar" :texts="['非常不满意','不满意','一般','满意','非常满意']" />
        <t-textarea
            v-model="textComment"
            placeholder="输入你的评论吧！"
            :autosize="{ minRows: 10, }"
            :maxcharacter="100"
        ></t-textarea>
      </t-space>
    </t-dialog>
  </t-layout>

</template>

<style scoped>

</style>